#!/usr/bin/env bash
cmd=$( basename "$0" )
img="ts.knight:3.0.0.11.build1"
dockerName="ljs-knight-docker"

function usage() {
    echo "Usage: ${cmd} [-i | -n | -h]" 
    echo "      启动docker"
    echo "      -i: <docker_img>:<docker_tag>, 缺省: ${img}"
    echo "      -n: docker容器名称，缺省: ${dockerName}"
    echo "      -g: cada gpu容器"
    echo "      -h: 输出此信息"
    exit 1
}

gpu=false
shiftCnt=0
while getopts "i:n:gh" arg
do
    case "${arg}" in 
        g)
            gpu=true
            shiftCnt=$(( ${shiftCnt} + 1 ))
            ;;
        i)
            img="${OPTARG}"
            shiftCnt=$(( ${shiftCnt} + 2 ))
            ;;
        n)
            dockerName="${OPTARG}"
            shiftCnt=$(( ${shiftCnt} + 2 ))
            ;;
        *)
            usage
            ;;
    esac
done

shift ${shiftCnt}
if [ $# -gt 0 ]
then
    usage
fi

echo "Run image ${img}..."

hostDir="${HOME}/docker_homes/knight_home"
etcDir="${HOME}/sys/etc_knight"
# liujinsong on 161
user="1172"
group="502"
clientHome="/home/knight"

echo run docker image ${img}

# 先删除旧的container
docker container rm -f ${dockerName} 2> /dev/null

if ${gpu}
then
    gpuOpt='--gpus all'
else
    gpuOpt=''
fi

docker run \
    ${gpuOpt} \
    -u ${user}:${group}\
    --net host \
    --rm \
    -e DISPLAY=${DISPLAY} \
    -v /tmp/.X11-unix/:/tmp/.X11-unix/ \
    -v ${HOME}/.Xauthority:${clientHome}/.Xauthority \
    -v ${etcDir}/group:/etc/group:ro \
    -v ${etcDir}/sudoers:/etc/sudoers:ro \
    -v ${etcDir}/passwd:/etc/passwd:ro \
    -v ${etcDir}/shadow:/etc/shadow:ro \
    -v ${hostDir}:${clientHome} \
    -v ${HOME}/bin:${clientHome}/bin \
    -v ${HOME}/work/ts.knight-modelzoo:${clientHome}/ts.knight-modelzoo \
    -v ${HOME}/work/ts.knight-sdk:${clientHome}/ts.knight-sdk \
    -v ${HOME}/model_zoo:${clientHome}/model_zoo \
    -v ${HOME}/datasets:${clientHome}/datasets \
    -v ${HOME}/exer:${clientHome}/exer \
    -v ${HOME}/tmp:${clientHome}/tmp \
    -w ${clientHome} \
    --name "${dockerName}" \
    -it \
    ${img}
